package edu.ntu.im.p2ptrade.metadata;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

import net.jxta.exception.PeerGroupException;
import net.jxta.peergroup.PeerGroup;
import net.jxta.share.CMS;
import net.jxta.share.ContentManager;
import net.jxta.share.FileContent;
import edu.ntu.im.p2ptrade.P2PTrade;
import edu.ntu.im.p2ptrade.entity.Item;

public class MetaDataManager {

	private static MetaDataManager me;

	private CMS CMContext;

	private ContentManager contentManager;
	
	private HashMap<String, FileContent> shares = new HashMap<String, FileContent>();

	public static synchronized MetaDataManager getInstance() {
		if (me == null) {
			me = new MetaDataManager();
		}
		return me;
	}

	private MetaDataManager() {
		CMContext = new CMS();
		PeerGroup pg = P2PTrade.getInstance().getPeerGroup();
		try {
			CMContext.init(pg, null, null);
			File cms = new File("./placeHolder");
			if (!cms.exists()) {
				cms.mkdir();
			}
			CMContext.startApp(cms);
			this.contentManager = CMContext.getContentManager();
		} catch (PeerGroupException e) {
			e.printStackTrace();
		}
	}

	public void publish(MetaData meta) throws MetaDataAlreadyPublished {
		if (this.shares.get(meta.getTitle())!=null){
			throw new MetaDataAlreadyPublished("meta data with same identifier existed!");
		}
		File placeHoleder = new File(meta.getTitle());

		try {
			if (!placeHoleder.exists()) {
				placeHoleder.createNewFile();
			}
			FileContent fc = this.contentManager.share(placeHoleder, meta.getTitle(), null, meta
					.getDetail());
			this.shares.put(meta.getTitle(), fc);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void unshare(MetaData meta){
		this.shares.remove(meta.getTitle());
	}

	private static String getShareId(PeerGroup pg) {
		if (null == pg) {
			return null;
		}

		URI u = pg.getPeerGroupID().toURI();
		String id = pg.getPeerGroupName() + "-" + u.toASCIIString();
		try {
			id = URLEncoder.encode(id, "UTF-8");
		} catch (UnsupportedEncodingException uee) {

		}
		return id;
	}

	

}
